<?php
/**
 * SyncService.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/11/16- 2:33 下午
 */

namespace common\services;


use common\dao\PddMallLogisticsDao;
use common\dao\PddMallProductDao;
use common\dao\PddMallProductSkusDao;
use common\models\PddBatchSyncLog;
use common\models\PddBatchSyncLogProducts;
use common\models\PddMallProductSkus;
use common\exception\ServicesException;
use common\helpers\ImagesHelper;
use common\models\PddUserMall;
use common\models\es\EsPddMallProductsSkus;
use common\models\PddMallProduct;

class SyncService
{

    /**
     * 同步店铺商品
     * @param array $product
     * @param array $skus
     * @return bool
     * @throws \api\exceptions\ServiceException
     * @throws \api\exceptions\ValidatorException
     * @throws \yii\db\Exception
     */
    public function syncProducts(array $product, array $skus = [])
    {
        /**
         * 写入主表
         */
        $mallProductDao = new PddMallProductDao();


        $mallProductInfo = $mallProductDao->getInfoByGoodsId($product['goods_id']);
        if ($product) {
            if (isset($product['image_url']) && !empty($product['image_url'])) {
                $product['image_url_base'] = md5(ImagesHelper::base64EncodeImage($product['image_url']));
            }
        }
        if (!$mallProductInfo) {
            $mallProductInfo = $mallProductDao->insertData($product);
        } else {

            $mallProductDao->updateData($mallProductInfo, $product);
        }

        $mallProductSkuDao = new PddMallProductSkusDao();
        if (count($skus)) {
            $mallProductSkuDao->batchDeleteAll(['goods_id' => $mallProductInfo->goods_id]);
//            $es = new EsPddMallProductsSkus();
//            $attributes = $es->attributes();
//            $es->syncDataSkuDelete($mallProductInfo->goods_id);
            foreach ($skus as $k => $sku) {
                $skus[$k]['spec_name'] = '';
                if ($sku['spec']) {
                    $skuname = json_decode($sku['spec'], true);
                    if ($skuname) {
                        foreach ($skuname as $k1 => $v1) {
                            $skus[$k]['spec_name'] .= $v1['spec_name'];
                        }
                    }
                }
                $skus[$k]['goods_id'] = $mallProductInfo->goods_id;
                $skus[$k]['uid'] = $mallProductInfo->uid;
                $skus[$k]['mall_id'] = $mallProductInfo->mall_id;
            }
            $mallProductSkuDao->batchInsert($skus);
//            $products = [];
//            $models = PddMallProductSkus::find()->where(['goods_id' => $mallProductInfo->goods_id])->all();
//
//
//            foreach ($models as $model) {
//                $product = [];
//                foreach ($attributes as $column) {
//                    $product[$column] = $model->$column;
//                }
//                $products[] = $product;
//            }
//            $res = $products ? $es->syncDataSku($products) : [];

        }

        return true;

    }


    /**
     * 同步商品运费模板
     * @param array $logistics
     * @return PddMallLogistics|null
     * @throws \api\exceptions\ValidatorException
     */
    public function syncLogistics(array $logistics)
    {

        $mallLogistics = new PddMallLogisticsDao();

        $mallLogisticsInfo = $mallLogistics->getInfoByTmplateId($logistics['template_id']);


        if (!$mallLogisticsInfo) {
            $mallLogisticsInfo = $mallLogistics->insertData($logistics);
        } else {

            $mallLogistics->updateData($mallLogisticsInfo, $logistics);
        }

        return $mallLogisticsInfo;

    }

    /**
     * 获取批量修改记录
     * @param int $page
     * @param int $pageSize
     * @param array $args
     * @return array
     */
    public function getListPage(int $page = 1, int $pageSize = 10, array $args = [])
    {
        $query = PddBatchSyncLogProducts::find();
        $query->select(['id', 'batchType', 'batch_no', 'uid', 'mall_id', 'goods_id', 'updated_at', 'aftercontent', 'beftercontent', 'status', 'error_info']);

        $query->where(['batchType' => $args['batchType']])
            ->andWhere(['type' => $args['type']])->andWhere(['in','status',[1,2,3]])
            ->andWhere(['in','mall_id',$args['mall_id']]);
        $offset = ($page - 1) * $pageSize;
        /**
         * 默认按照id 倒叙排序
         */
        $count = $query->count();
        $query->orderBy('id DESC');
        $query->limit($pageSize)->offset($offset);
        $list = $query->asArray()->all();
        if($list){
            foreach($list as $k=>$v){
                $detailInfo = PddMallProduct::find()->where([
                    'goods_id' => $v['goods_id'],
                    'uid' => $v['uid'],
                    'mall_id' => $v['mall_id'],
                ])->asArray()->one();

                $mallInfo = PddUserMall::find()->where([
                    'mall_id' => $v['mall_id']

                ])->one();
                $list[$k]['mall_name'] = $mallInfo?$mallInfo->mall_name:'';
                $list[$k]['updated_at'] = date("Y-m-d:H:i:s",$list[$k]['updated_at']);
                $list[$k]['image_url'] = $detailInfo?$detailInfo['image_url']:'';
                $list[$k]['goods_name'] = $detailInfo?$detailInfo['goods_name']:'';
                $list[$k]['aftercontent'] = json_decode($list[$k]['aftercontent'],true);
                $list[$k]['beftercontent'] = json_decode($list[$k]['beftercontent'],true);
            }
        }
        return [$count, $list];

    }


    private function formatList(array $list)
    {
        $formatData = [];
        foreach ($list as $k => $item) {
            $tmp = [];
            $batchName = $this->getBatchName($item->batchType);
            $tmp['id'] = $item->id;
            $tmp['editGoodsJson'] = $item->editGoodsJson;
            $tmp['title'] = $batchName;
            $tmp['created_at'] = $item->created_at;
            $tmp['total_cnt'] = $item->total_cnt;
            $tmp['success_cnt'] = PddBatchSyncLogProducts::find()
                ->where(['batch_no' => $item->id, 'status' => 1])
                ->count();
            $tmp['fail_cnt'] = PddBatchSyncLogProducts::find()
                ->where(['batch_no' => $item->id, 'status' => 2])
                ->count();
            $tmp['unknown_cnt'] = PddBatchSyncLogProducts::find()
                ->where(['batch_no' => $item->id, 'status' => 3])
                ->count();
            $tmp['filter_cnt'] = PddBatchSyncLogProducts::find()
                ->where(['batch_no' => $item->id, 'status' => 4])
                ->count();
            $tmp['status'] = $item->status;
            $formatData[] = $tmp;
        }

        return $formatData;
    }

    public function getBatchName($batchType)
    {
        $name = '';
        if (isset($batchType) && !empty($batchType)) {
            switch ($batchType) {
                case 'title':
                    $name = '批量修改标题';
                    break;
                case 'tinyname':
                    $name = '批量修改短标题';
                    break;
                case 'onsale':
                    $name = '批量修改上下架状态';
                    break;
                case 'goodsdelete':
                    $name = '批量删除商品';
                    break;
                case 'presale':
                    $name = '批量修改预售状态';
                    break;
                case 'country':
                    $name = '批量修改货源地';
                    break;
                case 'transportid':
                    $name = '批量修改运费模版';
                    break;
                case 'deliverytype':
                    $name = '批量修改物流信息';
                    break;
                case 'deliverytype':
                    $name = '批量修改物流信息';
                    break;
                case 'other':
                    $name = '批量修改服务信息';
                    break;
                case 'market_price':
                    $name = '批量修改市场价';
                    break;
            }
        }
        return $name;
    }

    public function getDetail(int $id = 0)
    {
        $res = PddBatchSyncLog::find()
            ->where(['id' => $id])
            ->all();
        if (!$res) {
            throw new ServicesException('批次号不存在');
        }


    }

}
